import socket
import threading
import sys

class Client(object) :
    def __init__(self):
        self.host = socket.gethostbyname(socket.gethostname())
        # self.host='localhost'
        self.port = 5000
        self.addr = (self.host,self.port)
        self.buffer = 1024
        self.clientfd = socket.socket()#客户端描述符
        try:
            self.clientfd.connect(self.addr)
        except socket.error as e:
            print(e)
            print("Unable to connect")
            exit(0)


    def recvmsg(self):
        while True :
            try :
                recvData =self.clientfd.recv(self.buffer)
            except socket.error as msg :
                print(msg)

            if recvData :
                print(recvData.decode())
            else :
                print("\n Disconnected from chat server!")
                sys.exit()

    def sendmsg(self):
        while True :
            msg=input("\n")
            self.clientfd.sendall(msg.encode())

if __name__ == '__main__':
    c=Client()
    sendT=threading.Thread(target=c.sendmsg)
    recvT=threading.Thread(target=c.recvmsg)

    sendT.start()
    recvT.start()

    sendT.join()
    recvT.join()
